<template>
  <el-dialog
    v-if="dialogVisible"
    width="400px"
    :title="title"
    :lock-scroll="false"
    :visible.sync="dialogVisible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item prop="parentId" label="上级部门">
        <TreeSelect :props="{children: 'children', label: 'name', value: 'id'}" :data="treeData" :value="form.parentId" clearable filterable @input="parentIdInput" />
      </el-form-item>
      <el-form-item prop="name" label="部门名称">
        <el-input v-model="form.name" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item prop="description" label="部门描述">
        <el-input v-model="form.description" type="textarea" placeholder="请输入部门描述" :autosize="{ minRows: 4, maxRows: 8}" :maxlength="100" show-word-limit />
      </el-form-item>
      <el-form-item prop="sorted" label="排序">
        <el-input-number v-model="form.sorted" class="w_100" :min="1" :max="9999" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { add, edit, getInfo, getTree } from '@/api/dept'
import TreeSelect from '@/components/TreeSelect'
import tree from 'element-ui/packages/tree'

export default {
  name: 'SaveOrEditVue',
  components: { TreeSelect },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    },
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      title: '新增',
      treeData: [],
      form: {
        parentId: undefined,
        name: '',
        sorted: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        sorted: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    tree() {
      return tree
    }
  },
  created() {
    this.getTree()
    switch (this.type) {
      case 'add':
        this.title = '新增'
        if (this.id) {
          this.form.parentId = this.id.toString()
        }
        break
      case 'edit':
        this.title = '编辑'
        getInfo(this.id).then(res => {
          this.form = res.data
          this.form.parentId = this.form.parentId.toString()
        })

        this.removeNodeById(this.treeData, this.id)
        break
      default:
        break
    }
  },
  methods: {
    getTree() {
      getTree({}).then(res => {
        this.treeData = [{
          id: '0',
          parentId: -1,
          name: '顶级',
          children: res.data
        }]
      })
    },
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          switch (this.type) {
            case 'add':
              add(this.form).then(res => {
                this.$message.success('添加成功')
                this.handleGetList()
                this.handleClose()
              })
              break
            case 'edit':
              edit(this.form).then(res => {
                this.$message.success('编辑成功')
                this.handleGetList()
                this.handleClose()
              })
              break
            default:
              break
          }
        }
      })
    },
    parentIdInput(data) {
      this.form.parentId = data.toString()
    },
    handleGetList() {
      this.$emit('getData')
    },
    handleClose() {
      this.$emit('handleClose')
    },
    removeNodeById(data, id) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i]

        if (item.id === id) {
          data.splice(i, 1) // 删除当前节点
          i-- // 索引回退一位，因为删除了一个元素
        } else if (item.children && Array.isArray(item.children)) {
          // 递归处理子节点
          this.removeNodeById(item.children, id)
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">

</style>
